package com.app.shop.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;

/**
 * 微信操作工具类
 */
public class WxUtil {

//    @Value("${wxAppId}")
//    private static String wxAppId;
//    @Value("${wxAppSecret}")
//    private static String wxAppSecret;

    /**
     * 获取openid
     * @param code
     * @return
     */
    public static JSONObject getWxUserOpenid(String code) {

        String wxAppId="wxd29c7ee996c7abed";
        String wxAppSecret="98476f77745bcc4625bd5349b0d61a6f";
        //拼接url
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
        url.append("appid=");//appid设置
        url.append(wxAppId);
        url.append("&secret=");//secret设置
        url.append(wxAppSecret);
        url.append("&js_code=");//code设置
        url.append(code);
        url.append("&grant_type=authorization_code");
        JSONObject res=null;
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            res = JSONObject.parseObject(content);//把信息封装为json
        } catch (Exception e) {
            e.printStackTrace();
        }
        //"session_key":"EP4aFC6tGP1sH2vX1XVVhA=="
        //"openid":"oQn5r5RMu4nMSfYSLpkbZ-l_qmlQ"}
        return res;
    }

}
